package paim.wingchun.view.componentes.table;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.swing.RowFilter;


public class WC_RowFilter extends RowFilter<WC_TableModel, Integer> {

    private int[] columns;

    private Matcher matcher;

    public WC_RowFilter(Pattern regex, int[] columns) {
        checkIndices(columns);
        this.columns = columns;
        if ( regex == null )
            throw new IllegalArgumentException("Pattern regex nao pode ser nula");
        matcher = regex.matcher("");
    }

    private static void checkIndices(int[] columns) {
        for ( int i = columns.length - 1; i >= 0; i-- ) {
            if ( columns[i] < 0 )
                throw new IllegalArgumentException("Indice deve ser  >= 0");
        }
    }

    @Override
    public boolean include(RowFilter.Entry<? extends WC_TableModel, ? extends Integer> entry) {

        int count = entry.getValueCount();
        if ( columns.length > 0 ) {
            for ( int i = columns.length - 1; i >= 0; i-- ) {
                int index = columns[i];
                if ( index < count ) {
                    if ( incluir(entry, index) )
                        return true;
                }
            }
        }
        else {
            while ( --count >= 0 ) {
                if ( incluir(entry, count) )
                    return true;
            }
        }
        return false;
    }

    private boolean incluir(Entry<? extends WC_TableModel, ? extends Integer> entry, int index) {
        matcher.reset(entry.getStringValue(index));
        return matcher.find();
    }

    public static <M, I> RowFilter<WC_TableModel, Integer> stringFilter(String regex, int flags,
            int... indices) {
        return (RowFilter<WC_TableModel, Integer>) new WC_RowFilter(
                Pattern.compile(regex, flags), indices);
    }
}
